package org.csu.mypetstore.controller;

//import com.sun.org.apache.xpath.internal.operations.Mod;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    CartService cartService;
    @Autowired
    CatalogService catalogService;

    @GetMapping("/proceedToCheckout")
    public String proceedToCheckout( HttpSession session, Model model ) {
        Account account = (Account) session.getAttribute( "account" );

        Cart cart = (Cart) session.getAttribute( "cart" );
        if ( null == account || !account.isAuthenticated() ) {
            model.addAttribute( "message", "You must sign on before attempting to check out. Please sign on and try checking out again." );
            return "account/signin";
        }

        for(int i=0;i<cart.getCartItemList().size();i++) {
            Item item = catalogService.getItem(cart.getCartItemList().get(i).getItem().getItemId());
            if(cart.getCartItemList().get(i).getCartQuantity() > item.getStockQuantity()) {
                model.addAttribute("msg", "Sorry, "+
                        cart.getCartItemList().get(i).getItem().getItemId()
                        +" is sold out or not enough. There are "+cart.getCartItemList().get(i).getItem().getStockQuantity()+" Left.");
                Account loginAccount = (Account) session.getAttribute( "account" );
                Cart myCart = cartService.getCartByUsername( loginAccount.getUsername() );
                session.setAttribute( "cart", myCart );
                return "cart/cart";
            }
            if(item.getStatus().equals("F")) {
                model.addAttribute("msg", "Sorry, "+
                        cart.getCartItemList().get(i).getItem().getItemId()
                        +" is not for sale.");
                Account loginAccount = (Account) session.getAttribute( "account" );
                Cart myCart = cartService.getCartByUsername( loginAccount.getUsername() );
                session.setAttribute( "cart", myCart );
                return "cart/cart";
            }
        }

        Order order = new Order();
        order.initOrder( account, cart );
        session.setAttribute( "order", order );
        return "order/new_order";
    }

    @PostMapping("/submitOrder") //用户输入邮寄信息和账单信息后点击Submit按钮，跳转至订单预览界面；对应之前的ProcessOrderInfoServlet
    public String submitOrder( Order submittedOrder, HttpSession session ) {
        //获取购物车生成的订单
        Order order = (Order) session.getAttribute( "order" );
        //根据购物车生成的订单对象的字段补充订单信息
        submittedOrder.setUsername( order.getUsername() );
        submittedOrder.setOrderDate( order.getOrderDate() );
        submittedOrder.setCourier( order.getCourier() );
        submittedOrder.setTotalPrice( order.getTotalPrice() );
        submittedOrder.setLocale( order.getLocale() );
        submittedOrder.setStatus( order.getStatus() );
        submittedOrder.setLineItems( order.getLineItems() );

        System.out.println( submittedOrder.toString() );
        session.setAttribute( "order", submittedOrder );

        return "order/confirm_order";
    }

    @GetMapping("/comfirmOrder") //用户预览订单后点击确定，对应之前的SubmitOrderServlet
    public String comfirmOrder( HttpSession session, Model model ){
//        HttpSession session = request.getSession();

        Order order = (Order) session.getAttribute("order");
        session.setAttribute("lineItems",order.getLineItems());
        Account account = (Account)session.getAttribute("account");

        orderService.insertOrder(order);
        session.setAttribute( "order", order );

        //数据库减少库存数量
        Cart cart = (Cart) session.getAttribute("cart");
        for(int i=0;i<cart.getCartItemList().size();i++) {
            Item item = catalogService.getItem(cart.getCartItemList().get(i).getItem().getItemId());
            item.setCartQuantity(item.getCartQuantity()-cart.getCartItemList().get(i).getCartQuantity());
            catalogService.UpdateItem(item);
        }
        // 重置购物车
        cart = new Cart();
        session.setAttribute("cart",cart);

        cartService.clearCart( account.getUsername() );

//        cartDAO = new CartDAOImpl();
//        cartDAO.clearCart(account.getUsername());


        model.addAttribute("orderMsg", "Thank you, your order has been submitted.");

        return "order/view_order";
    }

    @GetMapping("/viewOrderList")
    public String viewOrderList( HttpSession session ){
        Account account = (Account)session.getAttribute("account");

        List<Order> orderList = orderService.getOrdersByUsername(account.getUsername());

        session.setAttribute("orderList",orderList);

        return "order/view_orderlist";
    }

    @GetMapping("viewOrderByOrderId")
    public String viewOrderByOrderId( String orderId, HttpSession session ){
        Integer orderIdInt = Integer.valueOf(orderId);

        Order order = orderService.getOrder(orderIdInt);

        session.setAttribute("order",order);
        return "order/view_order";
    }

}
